import React , {useEffect, useState} from 'react'
import { Form, Input, Button, Row, Col, message } from 'antd'
import { UserOutlined, LockOutlined, QrcodeOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import loginPic from '@/assets/login.png'
import logo from '@/assets/logo.png'
import { reqLogin, captchaImage } from '@/api/login'
import {saveTokenAction} from '@/store/actions/user'

import './index.less'

export default function Login() {
  const [verCode, setVerCode] = useState({
    codeImg:  '',
    uuid: ''
  })
  const navigate = useNavigate()
  const dispatch = useDispatch()

  /**
   * 获取验证码
   */
  const getCodeImg = async() => {
    const {img, uuid} = await captchaImage()   
    const newImg = 'data:image/gif;base64,'+img
    setVerCode({
      codeImg: newImg,
      uuid
    })
  } 

  useEffect(() => {
    getCodeImg()
  }, [])

	// 提交表单且数据验证成功后回调事件
	const onFinish = async(values) => {
    try{
      // 处理参数
      values ={...values, uuid: verCode.uuid}
      // 发送请求
      const {code, msg, token} = await reqLogin(values)
      if(code === 200) {
        message.success('登录成功', 1)
        //存入token
        await dispatch(saveTokenAction(token))
        //跳转到登录页面
        navigate('/', {replace: true}) 
        // 获取用户信息
        // await dispatch(getUserInfo())       
      }else {
        message.error(msg)
        getCodeImg()
      }
    }catch(err) {
      message.error('网络异常，请稍后重试!!')
    }
	}


	return (
		<div className='login'>
			<div className='login-box'>
				{/* 左侧图片 */}
				<img src={loginPic} alt='' className='login-l-img' />
				<div className='login-form'>
					{/* 右侧表单 */}
					<Form
						initialValues={{
							username: 'admin',
              password: '123456'
						}}
						onFinish={onFinish}
						autoComplete='off'
					>
						<Row className='login-form-title'>
							<Col>
								<img src={logo} alt='' className='logo' />
							</Col>
							<Col>
								<span className='title-label'>汇客CRM系统</span>
							</Col>
						</Row>
						<Form.Item
							name='username'
							rules={[
								{
									required: true,
									message: '用户名不能为空',
								},
							]}
						>
							<Input
								className='login-form-item'
								placeholder='账号'
								prefix={<UserOutlined />}
								bordered={false}
							/>
						</Form.Item>

						<Form.Item
							name='password'
							rules={[
								{
									required: true,
									message: '密码不能为空',
								},
							]}
						>
							<Input.Password
								className='login-form-item'
								placeholder=' 密码'
								prefix={<LockOutlined />}
								bordered={false}
							/>
						</Form.Item>
            <div className="login-code">
              <Form.Item
                name='code'
                rules={[
                  {
                    required: true,
                    message: '验证码不能为空',
                  },
                ]}
              >
                <Input
                    className='login-form-item'
                    placeholder='验证码'
                    prefix={<QrcodeOutlined />}
                    bordered={false}
                  />
              </Form.Item>
              <img src={verCode.codeImg} alt="" className='login-code-img' onClick={getCodeImg} />
            </div>



						<Form.Item>
							<Button 
                block
                type='primary' 
                size='large' 
                shape="round"
                htmlType='submit' 
                className='login-submit'
              >
								登录
							</Button>
						</Form.Item>
					</Form>
				</div>
			</div>
		</div>
	)
}
